<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * $appid = 'wx099845ee9271cbbd';
$appsecret = '4e5a295bb8836eced747de906e842968';
 */

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use app\models\Wechat\UserAccessToken;
use app\models\Child\TUserInfo;
use app\models\Child\Token;

class WechatController extends Controller {
    
    public $enableCsrfValidation = false;
    
    /*
     * 验证access_token和jsapi_ticket是否在有效期
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=wechat/check
     */
    public function actionCheck()
    {
        /*
         * 接收加密用的url
         */
        $urls1 = Yii::$app->request->get('url');
        if(strpos($urls1,'#') != false)
        {
            $urls = substr($urls1,0,strpos($urls1,'#'));
        }else{
            $urls = $urls1;
        }
        /*
         * 定义appid
         */
        $appid = 'wx099845ee9271cbbd';
        /*
         * 定义appsecret
         */
        $appsecret = '4e5a295bb8836eced747de906e842968';
        /*
         * 定义access_token创建时间为当前时间
         */
        $create_time = time();
        
        $tokens = new UserAccessToken();
        $list = $tokens->getToken();
        
        if(!empty($list))
        {
            $time = time();
            if($time-$list['create_time']>7200)
            {
                $code = $this->actionGettoken($appid,$appsecret,$create_time);
            }else{
                $code['access_token'] = $list['access_token'];
                $code['jsapi_ticket'] = $list['jsapi_ticket'];
            }
        }else{
            $code = $this->actionGettoken($appid,$appsecret,$create_time);
        }
        
        /*
         * 定义随机数$noncestr、时间戳$timestamp、地址$url
         */
        $length = 16;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $noncestr = "";
        for ($i = 0; $i < $length; $i++) {
          $noncestr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $timestamp = time();
        
//        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        
        /*
         * 字符串排序
         */
        $tmpstr = 'jsapi_ticket='.$code['jsapi_ticket'].'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$urls;
        /*
         * sha1加密
         */
        $signature = sha1($tmpstr);
        
        $data['appid'] = $appid;
        $data['timestamp'] = $timestamp;
        $data['noncestr'] = $noncestr;
        $data['signature'] = $signature;
        $data['urls1'] = $urls1;
        $data['urls'] = $urls;
        $data['jsapi_ticket'] = $code['jsapi_ticket'];
        
        $res['code'] = 1;
        $res['info'] = "获取配置信息成功";
        $res['data'] = $data;
        
        return json_encode($res);
        
    }
    
    /*
     * 获取access_token
     */
    public function actionGettoken($appid,$appsecret,$create_time)
    {
        
        /*
         * 定义请求的url
         */
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        /*
         * 调用获取access_token方法
         */
        $access_token = $this->actionTakecurl($url);
        
        $jsapi_ticket = $this->actionGetticket($access_token);
            
        $code['access_token'] = $access_token;
        $code['jsapi_ticket'] = $jsapi_ticket;
        
        /*
         * 将access_token写入数据库做全局保存
         */
        $tokens = new UserAccessToken();
        
        $result = $tokens->setToken($access_token,$create_time,$jsapi_ticket);
        
        if($result)
        {
            return $code;
        }else{
            return "获取失败，请稍后重试";
        }
        
    }
    
    /*
     * 获取jsapi_ticket
     */
    public function actionGetticket($access_token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
        
        $jsapi_ticket = $this->actionDocurl($url);
        
        return $jsapi_ticket;
    }
    
    /*
     * curl模拟请求
     */
    public function actionTakecurl($url)
    {
        /*
         * 开启curl
         */
        $ch = curl_init();
        /*
         * 设置传输选项及地址
         */
        curl_setopt($ch,CURLOPT_URL,$url);
        /*
         * 以文件流形式返回
         */
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        /*
         * 发送curl请求
         */
        $arr = curl_exec($ch);
        /*
         * 解除json编码
         */
        $arrs = json_decode($arr,TRUE);
        $access_token = $arrs['access_token'];
        /*
         * 关闭资源
         */
        curl_close($ch);
        
        return $access_token;
    }
    
    /*
     * curl模拟请求
     */
    public function actionDocurl($url)
    {
        /*
         * 开启curl
         */
        $ch = curl_init();
        /*
         * 设置传输选项及地址
         */
        curl_setopt($ch,CURLOPT_URL,$url);
        /*
         * 以文件流形式返回
         */
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        /*
         * 发送curl请求
         */
        $arr = curl_exec($ch);
        /*
         * 解除json编码
         */
        $arrs = json_decode($arr,TRUE);
        $jsapi_ticket = $arrs['ticket'];
        /*
         * 关闭资源
         */
        curl_close($ch);
        
        return $jsapi_ticket;
    }
    
    /*
        获取access_token
     */
    public function actionGetAccessToken($appid,$appsecret)
    {
        /*
            定义请求的url地址
         */
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $access_token = $this->actionTakeAccessToken($url);

        return $access_token;
    }

    /*
        模拟curl请求获取access_token
     */
    public function actionTakeAccessToken($url)
    {
        /*
                开启curl
         */
        $ch = curl_init();
        /*
                设置传输选项及地址
         */
        curl_setopt($ch,CURLOPT_URL,$url);
        /*
                以文件流形式返回
         */
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        /*
                发送curl请求
         */
        $arr = curl_exec($ch);
        /*
                解除json编码
         */
        $arrs = json_decode($arr,TRUE);
        $access_token = $arrs['access_token'];
        /*
                关闭资源
         */
        curl_close($ch);

        return $access_token;
    }
    
    /*
     * 推送模板消息(问卷调查)
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=wechat/sendtemplet
     * 参数：
     *      用户ID：user_id
     */
    public function actionSendtemplet()
    {
        $appid = 'wx099845ee9271cbbd';
        $appsecret = '4e5a295bb8836eced747de906e842968';
        $create_time = time();
        $tokens = new Token();
        $lists = $tokens->getToken();
        if(!empty($lists))
        {
            $time = time();
            if(($time-$lists['create_time'])>7200)
            {
                $access_token = $this->actionGetAccessToken($appid,$appsecret);
                $tokens->setToken($access_token,$create_time);
            }else{
                $access_token = $lists['access_token'];
            }
        }else{
            $access_token = $this->actionGetAccessToken($appid,$appsecret);
            $tokens->setToken($access_token,$create_time);
        }
        /*
         * 定义url
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        
        /*
         * 接值
         */
        $rel_id = Yii::$app->request->post('rel_id');
        $booking_id = Yii::$app->request->post('booking_id');
        $user_id = Yii::$app->request->post('user_id');
        $patient_id = Yii::$app->request->post('patient_id');
        $doctor_id = Yii::$app->request->post('doctor_id');

        /*
         * 通过user_id查询openid
         */
        $user = new TUserInfo();
        $list = $user->getOpenId($user_id);
        if(!empty($list))
        {
            $arr = array(
                "touser" => $list['open_id'],
//                "template_id" => "Sqry29vTYzuH2cwhddMDvyFJ7l6a9b0BZb1MYmLhQQI",
		"template_id" => "hB3GXEYb_83oU0oVMQDiR8BGHrlxR-p9wyJMnoIunSE",
                "url" => "http://testxrtn.ggling.com/xetn/request.html?booking_id=".$booking_id."&user_id=".$user_id."&patient_id=".$patient_id."&doctor_id=".$doctor_id."&rel_id=".$rel_id,
                "data" => array(
//                    "name" => array(
//                        "value" => $list['user_name'],
//                        "color" => 'red',
//                    ),
                ),
            );
            /*
             * 数组转换成json
             */
            $json = json_encode($arr);
            
            $result = $this->actionHttps_request($url,$json);
	    $result = json_decode($result,true);
            if($result['errcode'] == 0)
            {
                $res['code'] = 1;
                $res['info'] = "问卷调查已推送成功，请用户接受";
            }else{
                $res['code'] = 0;
                $res['info'] = "推送失败，请重试";
            }
        }
        return json_encode($res);
        
    }
    
    /*
     * 推送模板消息(症状)
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=wechat/senddisease
     * 参数：
     *      用户ID：user_id
     */
    public function actionSenddisease()
    {
        $appid = 'wx099845ee9271cbbd';
        $appsecret = '4e5a295bb8836eced747de906e842968';
        $create_time = time();
        $tokens = new Token();
        $lists = $tokens->getToken();
        if(!empty($lists))
        {
            $time = time();
            if(($time-$lists['create_time'])>7200)
            {
                $access_token = $this->actionGetAccessToken($appid,$appsecret);
                $tokens->setToken($access_token,$create_time);
            }else{
                $access_token = $lists['access_token'];
            }
        }else{
            $access_token = $this->actionGetAccessToken($appid,$appsecret);
            $tokens->setToken($access_token,$create_time);
        }
        
        /*
         * 定义url
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        
        /*
         * 接值
         */
        $treatment_id = Yii::$app->request->post('treatment_id');
        $booking_id = Yii::$app->request->post('booking_id');
        $user_id = Yii::$app->request->post('user_id');
        $patient_id = Yii::$app->request->post('patient_id');
        $doctor_id = Yii::$app->request->post('doctor_id');

        /*
         * 通过user_id查询openid
         */
        $user = new TUserInfo();
        $list = $user->getOpenId($user_id);
        if(!empty($list))
        {
            $arr = array(
                "touser" => $list['open_id'],
                "template_id" => "ZN6OALEZGYbfwyLlTyZ4F82r1oBNwJG4748ceeu4k6A",
                "url" => "http://testxrtn.ggling.com/xetn/request2.html?booking_id=".$booking_id."&user_id=".$user_id."&patient_id=".$patient_id."&doctor_id=".$doctor_id."&treatment_id=".$treatment_id,
                "data" => array(
//                    "name" => array(
//                        "value" => $list['user_name'],
//                        "color" => 'red',
//                    ),
                ),
            );
            /*
             * 数组转换成json
             */
            $json = json_encode($arr);
            
            $result = $this->actionHttps_request($url,$json);
	    $result = json_decode($result,true);
            if($result['errcode'] == 0)
            {
                $res['code'] = 1;
                $res['info'] = "问卷调查已推送成功，请用户接受";
            }else{
                $res['code'] = 0;
                $res['info'] = "推送失败，请重试";
            }
        }else{
	    $res['code'] = 2;
	    $res['info'] = "该用户不存在";
	}
        return json_encode($res);
        
    }
    
    /*
     * https请求
     */
    public function actionHttps_request($url,$json)
    {
        /*
            开启curl
         */
        $ch = curl_init();
        /*
            设置传输选项及地址
         */
        curl_setopt($ch,CURLOPT_URL,$url);
        /*
            以文件流形式返回
         */
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        /*
            post方式
         */
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$json);
        /*
            发送curl请求
         */
        $arr = curl_exec($ch);
	
	return $arr;
        
    }
    
}

